package com.ruoyi.loginrisk.controller;

import com.ruoyi.loginrisk.service.ISysLoginRiskService;
import com.ruoyi.loginrisk.utils.CurrentAddressLocator;
import com.ruoyi.loginrisk.utils.DeviceInfoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.ruoyi.loginrisk.utils.IpUtil.getIp;

@RestController
@RequestMapping("/loginrisk")
public class LoginRiskController {

    private final ISysLoginRiskService loginRiskService;

    @Autowired
    public LoginRiskController(ISysLoginRiskService loginRiskService) {
        this.loginRiskService = loginRiskService;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, Object> loginInfo) throws Exception {
        String username = (String) loginInfo.get("username");
        String ip = String.valueOf(getIp()).substring(1);
        String loginLocation = CurrentAddressLocator.getCurrentAddress();
        String os = DeviceInfoUtils.getHostName();
        Date loginTime = new Date();
        Object userIdObj = loginInfo.get("userId");
        Long userId = null;
        if ((userIdObj instanceof Integer)){
            userId = ((Integer) userIdObj).longValue();
        }else if (userIdObj instanceof String) {
            userId = Long.parseLong((String) userIdObj);
        }else {
            userId = (Long) userIdObj;
        }

        Map<String, Object> riskResult = loginRiskService.judgeAndRecordLoginRisk(userId, username, ip, loginLocation, os, loginTime);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("isRisky", riskResult.get("isRisky"));
        result.put("riskReason", riskResult.get("riskReason"));
        return result;
    }
}